<template>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        :close-on-press-escape="false" @close="cancel">
        <el-form :model="form" ref="form" :disabled="isDis" label-width="110px" label-position="right"
            :rules="formRules">
            <div class="title">档期信息</div>
            <el-form-item label="档期类型" prop="schedule_type">
                <el-radio-group v-model="form.schedule_type" @input="typeRadio">
                    <el-radio label="0">主持人</el-radio>
                    <el-radio label="1">督导</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="日期" prop="schedule_date">
                <el-date-picker v-model="form.schedule_date" @change="getdata" type="date" placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="合作公司" prop="company_type">
                <el-radio-group v-model="form.company_type" @input="companyRadio">
                    <el-radio label="0">合作公司</el-radio>
                    <el-radio label="1">其他公司</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="partner_company_id" v-if="form.company_type == '0'" label=" ">
                <el-select v-model="form.partner_company_id" placeholder="请选择公司" filterable @change="changeCompany">
                    <el-option v-for="(item, i) in firmList" :key="i" :label="item.partner_company_name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="company_name" v-else label=" ">
                <el-input v-model="form.company_name" placeholder="请输入公司名称"></el-input>
            </el-form-item>
            <el-form-item v-if="form.company_type == '0'" prop="partner_company_id" label="仪式酒店 ">
                <el-select v-model="form.partner_company_id" filterable placeholder="请选择仪式酒店" @change="changeHotel">
                    <el-option v-for="item in firmList" :key="item.id" :label="item.partner_company_name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-else prop="hotel_name" label="仪式酒店 ">
                <el-input v-model="form.hotel_name" placeholder="请输入仪式酒店名称"></el-input>
            </el-form-item>
            <el-form-item prop="ceremony_hall_id" label="仪式厅" v-if="form.company_type == '0'">
                <el-select v-model="form.ceremony_hall_id" filterable placeholder="请选择仪式厅" @change="hallChange">
                    <el-option v-for="item in hallList" :key="item.id" :label="item.ceremony_hall_name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="ceremony_hall_name" label="仪式厅" v-else>
                <el-input v-model="form.ceremony_hall_name" placeholder="请输入仪式厅名称"></el-input>
            </el-form-item>
            <el-form-item prop="ceremony_hall_remarks" label="仪式厅说明">
                <el-input v-model="form.ceremony_hall_remarks" placeholder="请输入仪式厅说明" type="textarea"
                    :autosize="{ minRows: 3 }" maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <div class="title">人员信息</div>
            <el-form-item prop="fixed_gear_id" label="定档人员">
                <el-select v-model="form.fixed_gear_id" filterable placeholder="请选择定档人员" @change="personChange">
                    <el-option v-for="item in personList" :key="item.id" :label="item.stage_name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <div class="title">价格信息</div>
            <el-form-item label="是否推荐单" prop="is_recommend">
                <el-radio-group v-model="form.is_recommend" @input="recommendType">
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="service_price" label="服务价格">
                <el-input v-model="form.service_price" type="number" :min="0" @input="servicePrice"></el-input>
            </el-form-item>
            <el-form-item prop="deposit" label="定金">
                <el-input v-model="form.deposit"></el-input>
            </el-form-item>
            <el-form-item prop="studio_settlement" label="工作室结算价">
                <el-input v-model="form.studio_settlement" type="number" :min="0" @input="studioPrice"></el-input>
            </el-form-item>
            <el-form-item prop="recommend_user" label="推荐人" v-if="form.is_recommend == '0'">
                <el-input v-model="form.recommend_user"></el-input>
            </el-form-item>
            <el-form-item prop="rebate" label="返利" v-if="form.is_recommend == '0'">
                <el-input v-model="form.rebate" @input="rebatePrice" type="number" :min="0"></el-input>
            </el-form-item>
            <el-form-item prop="profit" label="利润">
                <el-input v-model="form.profit"></el-input>
            </el-form-item>
            <div class="title">结账状态</div>
            <el-form-item label="婚庆结账" prop="wedding_is_checkout">
                <el-radio-group v-model="form.wedding_is_checkout">
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="工作室结账" prop="studio_is_checkout">
                <el-radio-group v-model="form.studio_is_checkout">
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <div class="title">其他信息</div>
            <el-form-item label="当前确认截图" prop="ceremony_hall_img">
                <el-upload :action="fileUrl" :limit="5" :on-success="sucessImg" :on-error="errorImg"
                    accept=".png,.jpg,.jpeg" :file-list="imgFileList" :http-request="uploadHttp" list-type="picture"
                    :on-remove="deleteImg" :show-file-list="true" :before-upload="beforeImg">
                    <div class="uploadDiv" v-if="!isDis && imgFileList.length != 5">
                        <i class="el-icon-plus"></i>
                    </div>
                </el-upload>
            </el-form-item>
            <el-form-item prop="remarks" label="备注">
                <el-input v-model="form.remarks" type="textarea" :autosize="{ minRows: 3 }" maxlength="50"
                    show-word-limit></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="saveUsser" :disabled="isDis">确定</el-button>
        </div>
    </el-dialog>
</template>
<script>
import util from '../../utils/request';
export default {
    computed: {
        fileUrl() {
            return util.defaults.baseURL + 'api/uploadFile'

        }

    },
    data() {
        return {
            imgFileList: [],
            title: '新增档期',
            dialogFormVisible: false,
            isDis: false,
            firmList: [],
            personList: [],
            hallList: [],
            form: {
                schedule_type: '0',
                schedule_date: '',
                company_type: '0',
                partner_company_id: '',
                company_name: '',
                hotel_name: '',
                ceremony_hall_id: '',
                ceremony_hall_name: '',
                ceremony_hall_remarks: '',
                fixed_gear_id: '',
                fixed_gear_name: '',
                is_recommend: '1',
                service_price: 0,
                deposit: 0,
                studio_settlement: 0,
                recommend_user: '',
                rebate: 0,
                profit: 0,
                wedding_is_checkout: '1',
                studio_is_checkout: '1',
                remarks: '', archive_img: ''
            },
            // hotelId: '',
            formRules: {
                schedule_type: [{ required: true, message: '请选择档期类型', trigger: 'blur' }],
                schedule_date: [{ required: true, message: '请选择档期日期', trigger: 'blur' }],
                company_type: [{ required: true, message: '请选择公司类型', trigger: 'blur' }],
                partner_company_id: [{ required: true, message: '请选择合作公司', trigger: 'change' }],
                company_name: [{ required: false, message: '请输入合作公司', trigger: 'blur' }],
                hotel_name: [{ required: true, message: '请输入仪式酒店', trigger: 'blur' }],
                ceremony_hall_id: [{ required: false, message: '请选择仪式厅', trigger: 'change' }],
                ceremony_hall_name: [{ required: false, message: '请输入仪式厅', trigger: 'blur' }],
                fixed_gear_id: [{ required: true, message: '请选择定档人员', trigger: 'blur' }],
                is_recommend: [{ required: true, message: '请选择是否推荐单', trigger: 'blur' }],
                service_price: [{ required: true, message: '请输入服务价格', trigger: 'blur' }],
                deposit: [{ required: true, message: '请输入定金', trigger: 'blur' }],
                studio_settlement: [{ required: true, message: '请输入工作室结算价', trigger: 'blur' }],
                wedding_is_checkout: [{ required: true, message: '请选择婚庆是否结账', trigger: 'blur' }],
                studio_is_checkout: [{ required: true, message: '请选择工作室是否结账', trigger: 'blur' }]
            }
        }
    },
    methods: {
        cancel() {
            this.$refs.form.resetFields()
            this.imgFileList = []
            this.dialogFormVisible = false
            this.isDis = false
        },
        hallChange(val) {
            if (val != '') {
                this.hallList.forEach(item => {
                    if (item.id == val) {
                        this.form.ceremony_hall_name = item.ceremony_hall_name
                    }
                })
            }
        },
        personChange(val) {
            if (val != '') {
                this.personList.forEach(item => {
                    if (item.id == val) {
                        this.form.fixed_gear_name = item.stage_name
                        this.getUserDetailmoney(val)
                    }
                })
            }else{
                this.form.service_price=0
            }
        },
        getUserDetailmoney(id){
            this.$api.getUserInfo(id).then(res=>{
                this.form.service_price=res.data.market_price
                this.servicePrice(res.data.market_price)
            }).catch(err=>{
                this.$message.error(err.message)
                this.form.service_price=0
                this.servicePrice(0)
            })
        },
        saveUsser() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.imgFileList.length > 0) {
                        let imgArr = []
                        this.imgFileList.forEach(item => {
                            imgArr.push(item.filename)
                        })
                        this.form.archive_img = imgArr.join(',')
                    }
                    // this.form.schedule_date = this.$parent.formatterDate(this.form.schedule_date)
                    console.log(this.form);
                    if (this.form.id) {
                        this.$api.updataCanInfo(this.form).then(res => {
                            this.$message.success('修改成功')
                            this.cancel()
                            this.$parent.restForm()
                        }).catch(err => {
                            this.$message.error(err.message)
                        })
                    } else {
                        this.$api.submitCanInfo(this.form).then(res => {
                            this.$message.success('新增成功')
                            this.cancel()
                            this.$parent.restForm()
                        }).catch(err => {
                            this.$message.error(err.message)
                        })
                    }
                }
            })
        },
        //合作公司列表
        getCompanyList() {
            this.$api.queryCanCompanyList().then(res => {
                this.firmList = res.data
            }).catch(err => {
                this.$message.error(err.message)
            })
        },
        //仪式厅列表
        getHallList(val) {
            this.$api.queryCanHallList({ partner_company_id: val }).then(res => {
                this.hallList = res.data
            }).catch(err => {
                this.$message.error(err.message)
            })
        },
        //人员信息-定档人员
        getPersonList(val) {
            this.$api.queryCanUserList({ occupation: val }).then(res => {
                this.personList = res.data
            }).catch(err => {
                this.$message.error(err.message)
            })
        },
        //档期类型change
        typeRadio(val) {
            console.log(val);
            this.getPersonList(val)
        },
        adduser() {
            this.title = '新增档期'
            this.dialogFormVisible = true
            this.form = {
                schedule_type: '0',
                schedule_date: '',
                company_type: '0',
                partner_company_id: '',
                company_name: '',
                hotel_name: '',
                ceremony_hall_id: '',
                ceremony_hall_name: '',
                ceremony_hall_remarks: '',
                fixed_gear_id: '',
                fixed_gear_name: '',
                is_recommend: '1',
                service_price: 0,
                deposit: 0,
                studio_settlement: 0,
                recommend_user: '',
                rebate: 0,
                profit: 0,
                wedding_is_checkout: '1',
                studio_is_checkout: '1',
                remarks: '',
                archive_img: ''
            }
            this.formRules.partner_company_id[0].required = true
            this.formRules.company_name[0].required = false
            // this.formRules.ceremony_hall_id[0].required = true
            // this.formRules.ceremony_hall_name[0].required = false
        },
        getUserDetail(id, val) {
            val == 'isdetail' ? this.isDis = true : this.isDis = false
            val == 'isdetail' ? this.title = '档期详情' : this.title = '编辑档期'
            this.$api.getCanItemInfo(id).then(res => {
                this.form = res.data
                this.getHallList(this.form.partner_company_id)
                if (res.data.company_type == '1') {
                    this.formRules.partner_company_id[0].required = false
                    this.formRules.company_name[0].required = true
                    // this.formRules.ceremony_hall_id[0].required = false
                    // this.formRules.ceremony_hall_name[0].required = true
                } else {
                    this.formRules.partner_company_id[0].required = true
                    this.formRules.company_name[0].required = false
                    // this.formRules.ceremony_hall_id[0].required = true
                    // this.formRules.ceremony_hall_name[0].required = false
                }
                // this.changeCompany()
                if (res.data.archive_img == '' || res.data.archive_img == null) {
                    this.imgFileList = []
                } else {
                    let imgArr = res.data.archive_img.split(',')
                    imgArr.forEach(item => {
                        this.imgFileList.push({
                            url: util.defaults.baseURL + 'files/' + item,
                            name: item.split('-')[1],
                            filename: item
                        })
                    })
                }
                this.dialogFormVisible = true
            }).catch(err => {
                this.$message.error(err.message)
            })
        },
        //日期change
        getdata(val) {
            this.form.schedule_date = this.$parent.formatterDate(val)
            console.log(this.$parent.formatterDate(val));

        },
        //合作公司type
        companyRadio(val) {
            if (val == '1') {
                this.form.partner_company_id = ''
                this.formRules.partner_company_id[0].required = false
                this.formRules.company_name[0].required = true
                this.form.hotel_name = ''
                this.form.ceremony_hall_id = '',
                    this.form.ceremony_hall_name = ''
                this.form.company_name = ''
                // this.formRules.ceremony_hall_id[0].required = false
                // this.formRules.ceremony_hall_name[0].required = true
            } else {
                this.form.ceremony_hall_id = ''
                this.company_name = ''
                this.formRules.company_name[0].required = false
                this.formRules.partner_company_id[0].required = true
                this.form.hotel_name = ''
                this.form.ceremony_hall_name = ''
                this.form.company_name = ''
                // this.formRules.ceremony_hall_id[0].required = true
                // this.formRules.ceremony_hall_name[0].required = false
            }
        },
        //合作公司下拉选择联动
        changeCompany(val) {
            console.log('监测到动力');

            this.form.ceremony_hall_id = ''
            if (val != '') {
                this.getHallList(val)
                this.firmList.forEach(item => {
                    if (item.id == val) {
                        this.form.hotel_name = item.partner_company_name
                        this.form.company_name = item.partner_company_name
                    }
                    // item.id == val ? this.form.hotel_name = item.name : ''
                })
                // this.changeCompany(val)
            } else {
                console.log('是空的了');

            }
        },
        //合作仪式厅
        changeHotel(val) {
            this.form.ceremony_hall_id = ''
            if (val != '') {
                this.firmList.forEach(item => {
                    if (item.id == val) {
                        this.form.hotel_name = item.partner_company_name
                        this.form.company_name = item.partner_company_name
                    }
                })
                this.getHallList(val)
            }
        },

        //推荐单类型选择
        recommendType(val) {
            this.form.rebate = 0
            this.form.recommend_user = ''
        },
        servicePrice(val) {
            console.log(val, val.length, val == '', val == null, val == true);
            if (this.form.is_recommend == '0') {
                this.form.profit = this.form.service_price - this.form.studio_settlement - this.form.rebate
            } else {
                this.form.profit = this.form.service_price - this.form.studio_settlement
            }
        },
        studioPrice(val) {
            if (this.is_recommend == '0') {
                this.form.rebate.length > 0 ? this.form.profit = this.form.service_price - this.form.studio_settlement - this.form.rebate : this.form.profit = this.form.service_price - 0 - this.form.rebate
            } else {
                this.form.profit = this.form.service_price - this.form.studio_settlement
            }
        },
        rebatePrice(val) {
            if (this.form.is_recommend == '0') {
                this.form.rebate.length > 0 ? this.form.profit = this.form.service_price - this.form.studio_settlement - this.form.rebate : this.form.profit = this.form.service_price - this.form.studio_settlement - 0
            } else {
                this.form.profit = this.form.service_price - this.form.studio_settlement
            }
        },
        uploadHttp(options) {
            const formData = new FormData();
            // 注意：这里我们使用Blob对象，以便可以指定文件名
            const file = new Blob([options.file], { type: options.file.type });
            // 对文件名进行UTF-8编码，使用encodeURIComponent处理非ASCII字符
            console.log('options', options.file.name);
            // const fileName = options.file.name
            const fileName = encodeURIComponent(options.file.name);
            formData.append(options.filename, file, fileName);
            const xhr = new XMLHttpRequest();
            xhr.open('POST', options.action, true);
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    options.onSuccess(xhr.response);
                } else {
                    options.onError(xhr.response);
                }
            };
            xhr.send(formData);
        },
        sucessImg(res) {
            let responseObj = typeof res === 'string' ? JSON.parse(res) : res;
            this.$message.success(responseObj.msg)
            this.imgFileList.push({ ...responseObj, url: util.defaults.baseURL + 'files/' + responseObj.filename, name: responseObj.filename.split('-')[1] })
        },
        errorImg(err) {
            this.$message.error('文件上传失败')
        },
        beforeImg(file) {
            const maxSize = 100 * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.error('文件大小不能超过100MB');
                return false
            } else {
                // 将文件名转换为UTF-8编码
                const encodedName = encodeURIComponent(file.name);
                // 创建一个新File对象，保留其他属性
                const newFile = new File([file], encodedName, { type: file.type });
                // 替换原始文件（注意：File对象是只读的，可能需要特殊处理）
                return newFile;
            }
        },
        deleteImg(flie, flieList) {
            this.imgFileList = flieList
        },
    },
    mounted() {
        this.getCompanyList()
        this.getPersonList('0')
    }
}
</script>
<style lang="less" scoped>
.title {
    font-size: 16px;
    font-weight: 500;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.title::before {
    content: '';
    display: inline-block;
    width: 5px;
    height: 20px;
    background-color: #409eff;
    margin-right: 5px;
}

.uploadDiv {
    width: 120px;
    height: 120px;
    border: 1px dashed #C0C4CC;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px;

    i {
        font-size: 25px;
        color: #909399;
    }
}

.uploadDiv:hover {
    border-color: #409eff;

    i {
        color: #409eff;
    }
}

/deep/.el-form-item {
    margin-bottom: 15px;
}

/deep/.el-input {
    width: 250px;
}

/deep/.el-textarea {
    width: 250px;
}
</style>
<style>
.el-upload-list--picture .el-upload-list__item {
    width: 300px;
}
</style>